<?php 

if(!empty($_SERVER['HTTP_X_REQUESTED_WITH']) && strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) == 'xmlhttprequest') {


	require_once 'libraries/function/validateAjax.php';
	$data = array();

	if($_GET['setNewAvatar'] == 1){
		$avatar = $_POST['newAvatar'];
		$tmpArray = explode('_', $avatar);
		$folder = $tmpArray[0] . '/' . $tmpArray[1] . '/' . $tmpArray[2] . '/';
		$agent = 'User-Agent: Mozilla/5.0 (Windows; U; Windows NT 5.1; en-US; rv:1.8.1.15) Gecko/20080623 Firefox/2.0.0.15';
		$url = IMAGE_URL . 'avatar/original/' . $folder . $avatar;
		$url = str_replace(" ", '%20', $url);
		$ch = curl_init();
		curl_setopt($ch, CURLOPT_USERAGENT, $agent);
		curl_setopt($ch, CURLOPT_FAILONERROR, 1);
		curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
		curl_setopt($ch, CURLOPT_URL, $url);
		curl_setopt($ch, CURLOPT_NOBODY, true);
		$result = curl_exec($ch);

		if($result !== false){
			$statusCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
			echo $statusCode;
			if($statusCode != 200){
			exit();
			}else{
				$model = new model();
				$model->where = "id = '" . $_SESSION['user']['id'] . "'";
				$data = array('avatar' => $avatar);
				$model->update('users', $data);
				$resultdel = file_get_contents(
					R_IMAGE_URL . 'avatar/index.php?file=' . urlencode($_SESSION['user']['avatar']), false, stream_context_create(array(
				        'http' => array(
				            'method' => 'DELETE' 
				        )
				   ))

				);

				$_SESSION['user']['avatar'] = $avatar;

			}

		}

	}

	

	if($_GET['validateTitle'] == 1){
		$validateAjax = new ValidateAjax();
		$validateAjax->validateTitle($_POST['txtTitle']);
		if($validateAjax->isError()){
			$errors = $validateAjax->getErrorMessages();
			echo json_encode($errors);

		}else{
			echo json_encode(array('errors'=>''));

		}

		exit();
	}



	if($_GET['validateDescription'] == 1){
		$validateAjax = new ValidateAjax();
		$validateAjax->validateDescription($_POST['txtDescription'], array( 'validateAlias'=>'txtDescription', 'validateDescription' => 'Mô tả'));
		if($validateAjax->isError()){
			$errors = $validateAjax->getErrorMessages();
			echo json_encode($errors);
		}else{
		echo json_encode(array('errors'=>''));
		}
		exit();
	}

	

	/*

	 *  Validate image form

	 */

	

	if($_GET['validatePostImage'] == 1){

		$catType = "image_type";
		$validateAjax = new ValidateAjax();
		$validateAjax->validateTitle($_POST['txtTitle']);
		$validateAjax->validateDescription($_POST['txtDescription'], array('validateAlias'=>'txtDescription', 'validateDescription' => 'Mô tả'));
		$validateAjax->validateFiles($_POST['uploadedFile']);
		$validateAjax->validateCategory($_POST['txtCat'], $catType);

		$validateAjax->validateAlbum($_POST['txtAlbum']);

		if($validateAjax->isError()){

			$errors = $validateAjax->getErrorMessages();

			echo json_encode($errors);

			exit();

		}else{

			$datetime = date('Y-m-d H:i:s');
			
			
			$table = 'post_image';
			$image = $_POST['uploadedFile'][0];
			unset($_POST['uploadedFile'][0]);
			$arrayCat = getCatAndSub($_POST['txtCat']);

			$data = array(
					'title'				=> $_POST['txtTitle'],
					'description'		=> $_POST['txtDescription'],
					'cat_id'			=> $arrayCat['cat'],
					'sub_id'			=> $arrayCat['sub'],
					'album_id'			=> $_POST['txtAlbum'],
					'image'				=> $image,
					'date_created'		=> $datetime,
					'username'				=> $_SESSION['user']['username'],
					'status'			=> 1,
			);

			$model = new Model();
			$model->insert($table, $data);
	
			$model->select = "id";

			$model->where = "username = '" . $_SESSION['user']['username'] . "'";

			$model->order = "id DESC";

			$model->limit = '1';

			$model->getdata('post_image');

			$result = $model->fetchOne();

			if($result){

				if(is_array($_POST['uploadedFile'])){

					foreach($_POST['uploadedFile'] as $file){

						$fileData = array(

									'post_id' => $result['id'],

									'image'		=> $file,

									'date_created'	=> $datetime

								);

						$model->insert('images', $fileData);

					}

				}

				

				$indexData = array(
					'post_id'	=> $result['id'],
					'name'		=> $_POST['txtTitle'],
					'is_image'	=> 1,
					'id_album'	=> $data['album_id'],
					'username'	=> $_SESSION['user']['username'],
					'status'	=> 1,
					'cat_id'	=> $arrayCat['cat'],
					'sub_id'	=> $arrayCat['sub'],
				);

				$model->insert('index_post', $indexData);

				

				$model->select = "id";
				$model->order = "id DESC";
				$model->limit = "1";
				$model->getdata('index_post');
				$resultNewest = $model->fetchOne();
				if($resultNewest){
				file_put_contents(BASE_PATH . '/libraries/data/newest.txt', $resultNewest['id']);
				}
			
				echo json_encode(array('errors'=>'', 'message'=>'Đăng bài thành công.'));
				exit();

			}else{
				echo json_encode(array('errors'=>array('error'=>'Có lỗi xảy ra, xin vui lòng thử lại.'), 'message'=>''));
				exit();

			}

		}

	}

	

	/*

	 *  Validate video post

	 */

	if($_GET['validatePostVideo'] == 1){
		$catType = "video_type";
		$validateAjax = new ValidateAjax();
		$validateAjax->validateTitle($_POST['txtTitle']);
		$validateAjax->validateDescription($_POST['txtDescription'], array('validateAlias'=>'txtDescription', 'validateDescription' => 'Mô tả'));
		$validateAjax->validateCategory($_POST['txtCat'], $catType);
		$validateAjax->validateAlbum($_POST['txtAlbum']);
		$video = $validateAjax->validateVideoSource($_POST['txtSourceUrl'], $_POST['txtSource']);



		if($validateAjax->isError()){
			$errors = $validateAjax->getErrorMessages();
			echo json_encode($errors);
			exit();
		}else{

			

			$datetime = date('Y-m-d H:i:s');
			$arrayCat = getCatAndSub($_POST['txtCat']);
			$model = new Model();
			$table = 'post_media';
			$content = $video->getContent();

			

			//$image = $content['items'][0]['snippet']['thumbnails']['standard']['url'];
			$image = $video->getImage($content['items'][0]['snippet']['thumbnails']);
			$data = array(
					'title'				=> $_POST['txtTitle'],
					'description'		=> $_POST['txtDescription'],
					'media_type'		=> $video->_alias,
					'cat_id'			=> $arrayCat['cat'],
					'sub_id'			=> $arrayCat['sub'],
					'album_id'			=> $_POST['txtAlbum'],
					'url'				=> $_POST['txtSourceUrl'],
					'image'				=> $image,
					'date_created'		=> $datetime,
					'username'			=> $_SESSION['user']['username'],
					'status'			=> 1,
			);
			$model->insert($table, $data);
			$model->select = "id, album_id";
			$model->where = "username = '".$_SESSION['user']['username']."'";
			$model->order = "id DESC";
			$model->limit = '1';
			$model->getdata('post_media');
			$result = $model->fetchOne();
			if($result){
				if(is_array($_POST['uploadedFile'])){
					foreach($_POST['uploadedFile'] as $file){
						$fileData = array(
								'post_id' => $result['id'],
								'image'		=> $file,
								'date_created'	=> $datetime
						);
						$model->insert('images', $fileData);
					}
				}

				$indexData = array(
						'post_id'	=> $result['id'],
						'name'		=> $_POST['txtTitle'],
						'is_video'	=> 1,
						'status'	=> 1,
						'id_album'	=> $result['album_id'],
						'username'	=> $_SESSION['user']['username'],
						'cat_id'	=> $arrayCat['cat'],
						'sub_id'	=> $arrayCat['sub']
				);

				$model->insert('index_post', $indexData);

				
				$model->select = "id";
				$model->order = "id DESC";
				$model->limit = "1";
				$model->getdata('index_post');
				$resultNewest = $model->fetchOne();
				if($resultNewest){
					file_put_contents(BASE_PATH . '/libraries/data/newest.txt', $resultNewest['id']);
				}
				echo json_encode(array('errors'=>'', 'message'=>'Đăng bài thành công.'));
				exit();
			}else{
				echo json_encode(array('errors'=>array('error'=>'Có lỗi xảy ra, xin vui lòng thử lại.'), 'message'=>''));
				exit();
			}
		}
	}

	if($_GET['validatePostText'] == 1){

		$catType = "text_type";
		$validateAjax = new ValidateAjax();
		//$validateAjax->validateMainImage($_POST['txtMainImage']);
		$validateAjax->validateTitle($_POST['txtTitle']);
		$validateAjax->validateDescription($_POST['txtDescription'], array('validateAlias'=>'txtDescription', 'validateDescription' => 'Mô tả'));
		$validateAjax->validateCategory($_POST['txtCat'], $catType);

		$validateAjax->validateAlbum($_POST['txtAlbum']);

		if($validateAjax->isError()){
			$errors = $validateAjax->getErrorMessages();
			echo json_encode($errors);
			exit();

		}else{

			

			$surl="content=".urlencode($_POST['txtDescription']);
			$url = IMAGE_URL . 'text/image.php';
			$resultContent = mycurl($surl,$url);
			$_POST['txtDescription'] = urldecode($resultContent);
			$arrayCat = getCatAndSub($_POST['txtCat']);
			$datetime = date('Y-m-d H:i:s');
			$model = new Model();
			$table = 'post_text';
			$image = $_POST['txtMainImage'];
			$data = array(

					'title'				=> $_POST['txtTitle'],
					'description'		=> $_POST['txtDescription'],
					'sdes'				=> $_POST['txtsdes'],
					'cat_id'			=> $arrayCat['cat'],
					'sub_id'			=> $arrayCat['sub'],
					'album_id'			=> $_POST['txtAlbum'],
					'image'				=> $image,
					'date_created'		=> $datetime,
					'username'			=> $_SESSION['user']['username'],
					'status'			=> 1,
			);

			$model->insert($table, $data);

				

			$model->select = "id";
			$model->where = "username = '" . $_SESSION['user']['username'] . "'";
			$model->order = "id DESC";
			$model->limit = '1';
			$model->getdata('post_text');
			$result = $model->fetchOne();

			if($result){

				if(is_array($_POST['uploadedFile'])){

					foreach($_POST['uploadedFile'] as $file){

						$fileData = array(
								'post_id' => $result['id'],
								'image'		=> $file,
								'date_created'	=> $datetime
						);

						$model->insert('images', $fileData);
					}
				}

	

				$indexData = array(
						'post_id'	=> $result['id'],
						'name'		=> $_POST['txtTitle'],
						'is_text'	=> 1,
						'status'	=> 1,
						'username'	=> $_SESSION['user']['username'],
						'cat_id'	=> $arrayCat['cat'],
						'sub_id'	=> $arrayCat['sub'],
						'id_album'	=> $_POST['txtAlbum']
				);

				$model->insert('index_post', $indexData);

				

				$model->select = "id";
				$model->order = "id DESC";
				$model->limit = "1";
				$model->getdata('index_post');
				$resultNewest = $model->fetchOne();
				if($resultNewest){
					file_put_contents(BASE_PATH . '/libraries/data/newest.txt', $resultNewest['id']);
				}

				echo json_encode(array('errors'=>'', 'message'=>'Đăng bài thành công.'));
				exit();

			}else{
				echo json_encode(array('errors'=>array('error'=>'Có lỗi xảy ra, xin vui lòng thử lại.'), 'message'=>''));
				exit();
			}

		}

	}

	

	if($_GET['createAlbum'] == 1){
		$validateAjax = new ValidateAjax();
		$validateAjax->validateAlbumTitle($_POST['txtAlbumTitle']);
		$validateAjax->validateDescription($_POST['txtAlbumDescription'], array('validateAlias'=>'txtAlbumDescription', 'validateDescription' => 'Mô tả album'));
		if($validateAjax->isError()){
			$errors = $validateAjax->getErrorMessages();
			echo json_encode($errors);
			exit();
		}else{

			$model = new Model();
			$table = 'album';
			$data = array(
					'name' =>	$_POST['txtAlbumTitle'],
					'username'	=> $_SESSION['user']['username'],
					'date_created'	=>	date('Y-m-d H:i:s'),
					'description'	=> $_POST['txtAlbumDescription']
					);

			$model->insert($table, $data);
			echo json_encode(array('errors'=>'', 'message' => 'Tạo album mới thành công.'));
			exit();
		}
	}

	

	if($_GET['reloadAlbum'] == 1){
		$model = new Model();
		$model->select = 'id, name';
		
		$model->where = "username = '" . $_SESSION['user']['username'] . "' or public=1";
		$model->getdata('album');
		$result = $model->fetchAll();
		
		$model->select = 'id';
		$model->order = 'id DESC';
		$model->limit = 1;
		$model->getdata('album');
		$resultLastest = $model->fetchOne();

		if($result){
			$return='<option  value="">Tùy Chọn Playlist ...</option>';
			foreach($result as $key => $value){
				if($resultLastest){
					if($resultLastest['id'] == $value['id']){
						$return .= '<option selected value="'.$value['id'].'">'.$value['name'].'</option>';
					}else{
						$return .= '<option value="'.$value['id'].'">'.$value['name'].'</option>';
					}
				}
			}
		}
		echo $return;
		exit();
	}

	/*
	 *  Return html form for creating album on the modal box
	 */


	if($_GET['albumBox'] == 1){
		echo returnAlbumBox();
	}
}


if(isset($_GET['feed_truyen'])){
	
		$val=$_GET['q'];
		
		$val=khongdau($val);
		
		$db=new db;
		
		$db->connect();
		$db->query("select id,ten from truyen where  alias like'%".mysql_real_escape_string($val)."%'");
		
		if($db->num_rows()>0){	
			$dt=$db->fetchAll();	
			foreach($dt as $row){				
					$answer[] = array("id"=>$row['id'],"text"=>$row['ten']);		
			}
		}else{ 
		$answer[] = array("id"=>"0","text"=>"Không Tìm Thấy Kết Qủa");
		}
		
		$db->close();
		
		echo json_encode($answer);
		exit();


}


if(isset($_GET['feed_chuong_list'])){

		$val=$_GET['tid'];
		$sql="select id,ten,thutu from truyen_chuong where  truyen_id=".intval($val)." order by thutu desc";
	
		$db=new db;
		
		$db->connect();
		$db->query($sql);
		if($db->num_rows()>0){	
			$dt=$db->fetchAll();
			$html=' <select name="chuong" id="chuong" onchange="get_chuong_data(this.value)" class="form-control" >
						<option value="">Chọn Chương------</option>
                                          
					
					 ';	
			foreach($dt as $row){				
					$html.= '<option value="'.$row['id'].'">Thứ Tự : '.$row['thutu'].' - '.$row['ten'].'</option>';		
			}
			$html.=' </select> ';
		}else{ 
				$html=' <select name="chuong" id="chuong"  class="form-control" >
						<option value="">Truyện chưa có chương nào</option>
                                          
					
					 ';	
		}
		
		$db->close();
		
		echo $html;
		exit();


}

if(isset($_GET['feed_chuong'])){
	
		$val=$_GET['id'];
		$db=new db;
		
		$db->connect();
		$db->query("select t.id,t.ten,t.thutu,t2.noidung from truyen_chuong as t,truyen_chuong_noidung as t2  where  t.id=".intval($val)." and t2.truyen_chuong_id= ".$val);
		if($db->num_rows()>0){	
			$dt=$db->fetchOne();	
			
		}else{ 
			$dt['error']='Không Tìm thấy chương';
		}
		
		$db->close();
		
		echo json_encode($dt);
		exit();


}

if(isset($_POST['chuong_add'])){
	$md=new Model;
	//Kiem tra chuong co image ko, neu co image thi set image = 1 va curl de download image ve-----
		$j=check_image($_POST['noidung']);
	if($j>0){
		$url="content=".urlencode($_POST['noidung'])."&name=mong.vn";	
		$_POST['noidung']=urldecode(mycurl($url,'http://sv1.khodo.info/khodo/images/text/image.php'));
	
		$image=1;
	}else{
		
		$image=0;
	}
	
	
	//Kiem tra thu tu chuong
	$md->query('select id from truyen_chuong where truyen_id='.intval($_POST['truyen']).' and thutu='.floatval($_POST['thutu']));
	if($md->num_rows()>0){
		$data['errors'][]='Thứ tự của chương này đã tồn tại, xin vui lòng kiểm tra lại !';
		echo json_encode($data);
		exit();
	}
	//End of kiem tra thu tu chuong
	
	$data=array(
			'truyen_id'=>intval($_POST['truyen_id']),
			'thutu' => mysql_real_escape_string($_POST['thutu']),
			'ten'=>mysql_real_escape_string(trim($_POST['ten'])),
			'alias'=>mysql_real_escape_string(khongdau(trim($_POST['ten']))),
			'user_upload'=>$_SESSION['user']['username'],
			'time_upload' =>date('Y-m-d H:i:s'),
			'image'=>$image
	);
	$md->insert('truyen_chuong',$data);
	
	$data2['noidung']=$_POST['noidung'];
	$data2['truyen_chuong_id']=$md->get_id();
	$md->insert('truyen_chuong_noidung',$data2);
	
}
if(isset($_POST['chuong_update'])){
	$md=new Model;
	//Kiem tra chuong co image ko, neu co image thi set image = 1 va curl de download image ve-----
	//Kiem tra thu tu chuong
	//Kiem tra permission, user level 4 thi chi duoc quyen update chuong cua minh, con lai duoc quyen update het
	
	//Kiem tra image có không
	$j=check_image($_POST['noidung']);
	if($j>0){
		$url="content=".urlencode($_POST['noidung'])."&name=mong.vn";	
		$_POST['noidung']=urldecode(mycurl($url,'http://sv1.khodo.info/khodo/images/text/image.php'));
	
		$image=1;
	}else{
		
		$image=0;
	}
	

	
	//Kiem tra thutu chuong
	$md->query('select id from truyen_chuong where truyen_id='.intval($_POST['truyen']).' and thutu='.mysql_real_escape_string(floatval($_POST['thutu'])).' and id!='.intval($_POST['chuong']));
	if($md->num_rows()>0){
		$data['errors'][]='Thứ tự của chương này đã tồn tại, xin vui lòng kiểm tra lại !';
		echo json_encode($data);
		exit();
	}
	//Kiem tra permission cua user
	if($_SESSION['user']['level']==4){
		//Check user có phải là người thêm truyện này ko, tiếp theo là check user đó có phải là người upload chương này không
		$md->query('select user_upload from truyen where id='.intval($_POST['truyen_id']));
		$per_1=0;
		if($md->num_rows()>0){
			$r=$md->fetchOne();
			if($r['user_upload']==$_SESSION['user']['username']){
				$per_1=1;
			}
		}else{die();}
		
			if($per_1!=1){
					$md->query('select user_upload from truyen_chuong where id='.intval($_POST['chuong']));
					$row=$md-fetchOne();
					
					
					if($row['user_upload']!=$_SESSION['user']['username']){
						$data['errors'][]='Bạn không có quyền update chương này, có vấn đề gì liên quan đến chương này xin vui lòng thông báo cho ban quản trị Mong.vn !';
						echo json_encode($data);
						exit();
					}
			}
	}
	//End of kiem tra permission cua user
	
	
	$md->where('id='.intval($_POST['chuong']));
	
	$data=array(
		//	'truyen_id'=>intval($_POST['truyen_id']),
			'thutu' => mysql_real_escape_string($_POST['thutu']),
			'ten'=>mysql_real_escape_string(trim($_POST['ten'])),
			'alias'=>mysql_real_escape_string(khongdau(trim($_POST['ten']))),
			'user_update'=>$_SESSION['user']['username'],
			'time_update' =>date('Y-m-d H:i:s'),
			'image'=>$image
	);
	$md->update('truyen_chuong',$data);
	
	$data2['noidung']=$_POST['noidung'];
	$md->where('truyen_chuong_id='.intval($_POST['chuong']));
	$md->update('truyen_chuong_noidung',$data2);
	
	
	exit();
	
}
function returnAlbumBox(){
	return '
	<div role="dialog" id="modalAlbumBox" class="modal fade" style="display: none;">
		<div class="modal-dialog modal-wide">
			<div class="modal-content">
				<div class="modal-header">
					<button type="button" class="close" data-dismiss="modal" aria-hidden="true">&times;</button>
					<h4 class="modal-title">Tạo playlist mới</h4>
				</div>
		        <div class="modal-body">
					<div>
						<input type="text" class="form-control" id="txtAlbumTitle" placeholder="Tên Playlist..." />
					</div>
					<br />
					<div>
						<textarea class="form-control" id="txtAlbumDescription" placeholder="Mô tả Playlist..."></textarea>
					</div>
					<br />
					<div>
						<button type="submit" class="btn btn-primary btn-sm" id="sumbmitAlbum">
	                    	<i class="glyphicon glyphicon-plus"></i>
		                    <span>Tạo</span>
		                </button>
					</div>
					<div style="clear:both"></div>
		        </div>
			</div><!-- /.modal-content -->
		</div>

		<script type="text/javascript">
			$(document).ready(function(){
				$("#sumbmitAlbum").on("click", function(e){
					$("#modalAlbumBox").find(".alert").remove();
					e.preventDefault();
					$.ajax({
						url : "index.php?module=user&act=ajax&createAlbum=1",
						type: "POST",
						data: {txtAlbumTitle: $("#txtAlbumTitle").val(), txtAlbumDescription : $("#txtAlbumDescription").val()},
						success: function(data){
							if(data) { 
								newData = $.parseJSON(data); 
								if(newData.errors){
									$.each(newData.errors, function(index, error){
										$("#" + index).parent().append("<div id=\'"+index+"_error\' class=\'alert alert-danger alert-dismissable\' style=\'display: none;\'><button type=\'button\' class=\'close\' data-dismiss=\'alert\' aria-hidden=\'true\'>&times;</button><strong>Lỗi!</strong>"+ error + "</div>");
										$("#" + index + "_error").slideDown("fast");
									});
								}else{
									if(newData.message){
										$.ajax({
											url: "index.php?module=user&act=ajax&reloadAlbum=1",
											type: "POST",
											success: function(dataAlbum){
												$("#txtAlbum").html(dataAlbum);
												$("#txtAlbum").select2({ width: "250" });
											},
										});
										$("#txtAlbum").html("");
										$("#modalAlbumBox").modal("hide");
										$("#txtAlbum").parent().append("<div id=\'txtAlbum_message\' class=\'alert alert-success alert-dismissable\' style=\'display: none;\'><button type=\'button\' class=\'close\' data-dismiss=\'alert\' aria-hidden=\'true\'>&times;</button>"+ newData.message + "</div>");
										$("#txtAlbum_message").slideDown("fast");
									}
								}
							}
						},
					});
				});
			});
		</script>
	</div>';
}



function returnVideoForm(){

	return

	'<form id="videoPostForm" class="userPostForm" role="form">

		

		<div class="form-group">	

			<div class="field_error" id="txtCat_error></div>

			<label for="txtCat">Danh mục:</label>

			<select id="txtCat" class="myNormalSelect">

				<option value="">Hài</option>	

				<option value="">Buồn</option>	

				<option value="">Bựa</option>	

				<option value="">Lãng mạng</option>	

			</select>

		</div>	<br />

			

		<div class="form-group">

			<div class="field_error" id="txtTitle_error></div>

			<label for="txtTitle">Tiêu đề:</label>

			<input type="text" class="form-control" id="txtTitle" placeholder="Nhập tiêu đề">

		</div><br />



		<div class="form-group">

			<div class="field_error" id="txtvideoUrl_error></div>

			<label for="txtvideoUrl">Video URL:</label>

			<input type="text" class="form-control" id="txtvideoUrl" placeholder="Nhập url">

		</div><br />



		<div class="form-group">

			<button type="submit" class="btn btn-primary">Đăng bài</button>

		</div>

	</form>';

}



function returnTextForm(){

	return

	'<form id="" class="userPostForm" role="form">

			

		<div class="form-group">	

			<div class="field_error" id="txtCat_error></div>

			<label for="txtCat">Danh mục:</label>

			<select id="txtCat" class="myNormalSelect">

				<option value="">Hài</option>	

				<option value="">Buồn</option>	

				<option value="">Bựa</option>	

				<option value="">Lãng mạng</option>	

			</select>

		</div>	<br />

			

		<div class="form-group">

			<div class="field_error" id="txtTitle_error></div>

			<label for="txtTitle">Tiêu đề:</label>

			<input type="text" class="form-control" id="txtTitle" placeholder="Nhập tiêu đề">

		</div><br />



		<div class="form-group">

			<div class="field_error" id="txtContent_error></div>

			<label for="txtContent">Nội dung:</label>

			<textarea class="form-control" rows="5" id="txtContent" placeholder="Nhập nội dung bài viết"></textarea>

		</div><br />

			

		<div class="form-group">

			<button type="submit" class="btn btn-primary">Đăng bài</button>

		</div>

	</form>';

}

function getCatAndSub($cat){
		$model1 = new Model();
		$model1->select = "*";
		$model1->where = "id = '" .$cat . "'";
		$model1->getdata('category');
		$result = $model1->fetchOne();
		
		if($result['p_id'] == 0 || $result['p_id'] == ''){
		
			$cat1 = $result['id'];
			$sub = 0;
		}else{
			$model1->select = '*';
			$model1->where = "id = '" . $result['p_id'] . "'";
			$model1->getdata('category');
			$resultFetch = $model1->fetchOne();
			
			$resultPCat = $resultFetch['id'];
			if($resultPCat) {$cat1 = $resultPCat; $sub = $cat;}
		}
		return array('cat'=>$cat1, 'sub'=>$sub);
	}

function check_image($data){
$data = mb_convert_encoding($data, 'HTML-ENTITIES', "UTF-8"); 
$dom = new DOMDocument;
 $dom->loadHTML($data); 
 $sxe = simplexml_import_dom($dom);

	$j=0;	
	 foreach ($sxe->xpath('//img[@src]') as $a)
	 {	
		
		$j++;
	 }
 return $j;
 }
 